import { asyncRouterMap, constantRouterMap } from 'src/router'

/**
 * 通过authority判断是否与当前用户权限匹配
 * @param menus
 * @param route
 */
function hasPermission (menus, route) {
  if (route.authority) {
    if (menus[route.authority] !== undefined) {
      return true
    } else {
      return false
    }
  } else {
    return true
  }
}

// function filterAsyncRouter2(asyncRouterMap, menus, menuDatas) {
//   const accessedRouters = asyncRouterMap.filter(route => {
//     if (hasPermission(menus, route)) {
//       route.name = menuDatas[route.authority].title
//       route.icon = menuDatas[route.authority].icon
//       if (route.children && route.children.length) {
//         route.children = filterAsyncRouter2(route.children, menus, menuDatas)
//       }
//       return true
//     }
//     return false
//   })
//   return accessedRouters
// }
/**
 * 递归过滤异步路由表，返回符合用户角色权限(即存在menus中code=authority)的路由表
 * @param asyncRouterMap
 * @param roles
 */
function filterAsyncRouter (asyncRouterMap, menuCode) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (hasPermission(menuCode, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, menuCode)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: asyncRouterMap
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GENERATE_ASYNC_ROUTES ({ commit }, menuCodes) {
      return new Promise(resolve => {
        // 通过code来过滤不再 menuCodes中的路由
        let menuRouter = filterAsyncRouter(asyncRouterMap, menuCodes)
        commit('SET_ROUTERS', menuRouter)
        resolve()
      })
    } // generate extra routes by edgardeng
  },
  getters: {
    addedRouters (state) {
      return state.addRouters
    },
    accessedRouters (state) {
      return state.routers
    },
    routerMenu (state) { // UI menu for home
      let len = state.routers.length
      let routerNew = []
      for (let i = 0; i < len; i++) {
        let item = state.routers[i]
        if (!item.hidden) {
          if (item.children) {
            let children = []
            for (let j = 0; j < item.children.length; j++) {
              let child = item.children[j]
              if (!child.hidden) {
                children.push(child)
              }
            }
            item.children = children
          }
          routerNew.push(item)
        }
      }
      return routerNew
    }
  }
}

export default permission
